package com.dubito.composenote.ui.screen

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.dubito.composenote.data.NotesDao
import com.dubito.composenote.model.Note
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

/**
 * author: LiLiang
 * createTime: 2022/10/6-11:58
 * remark:
 **/
class NoteViewModel(private val dao: NotesDao) : ViewModel() {

    val notes: Flow<List<Note>>
        get() = dao.getNotes()

    fun deleteNote(note: Note) {
        viewModelScope.launch(Dispatchers.IO) {
            dao.deleteNote(note)
        }
    }

    fun updateNote(note: Note) {
        viewModelScope.launch(Dispatchers.IO) {
            dao.updateNote(note)
        }
    }

    fun createNote(title: String, note: String, image: String? = null) {
        val noteModel = Note(title = title, note = note, imageUri = image)
        viewModelScope.launch(Dispatchers.IO) {
            dao.insertNote(noteModel)
        }
    }

    suspend fun getNote(id: Int): Note? {
        return dao.getNoteById(id)
    }
}

class NoteViewModelFactory(private val dao: NotesDao) : ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return NoteViewModel(dao = dao) as T
    }
}